<template>
  <div id="app">
    <!--   17783825177 8acy3l41g0shhlcurjweinryc5dl83jeuvgmy2xd8hib50r8
          15826112077 q0067g07wq9mo8ykgah7cngwkffdyi4elqnxkw9ztz0wq6jr
          fpyvwcdxsc8p888y2nbuljrwhkdpjrjmw680vx2wq8jxy7kf
    -->

    <div class="fixed-header">
      <el-button @click="cancelAction">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="addAction">确 定</el-button>
    </div>

    <div class="content-wrapper">
    <editor
      class="contentHtml"
      api-key="8acy3l41g0shhlcurjweinryc5dl83jeuvgmy2xd8hib50r8"
      :init="editorConfig"
      v-model="contentHtml"
    />
    </div>


    <PlutoDialog
      :visible.sync="dialogFormVisible"
      :config="dialogConfig"
      @confirm="handleConfirmConfigAction"
    >
      <!-- 自定义内容插槽 -->
      <template v-slot:content>
        <el-form :model="form" ref="ruleForm" :rules="rules">
          <el-form-item label="控件类型" prop="controlType"
                        :label-width="formLabelWidth">
            <el-select @change="handleControlTypeChange" v-model="form.controlType" placeholder="控件类型">
              <el-option label="输入框" value="1"></el-option>
              <el-option label="日期时间" value="2"></el-option>
              <el-option label="选择下拉框" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自定义字段key" prop="controlKey" v-if="dynamicFormItems.includes('controlKey')"
                        :label-width="formLabelWidth">
            <el-input v-model="form.controlKey" placeholder="自定义字段key" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="自定义字段名称" prop="controlTitle" v-if="dynamicFormItems.includes('controlTitle')"
                        :label-width="formLabelWidth">
            <el-input v-model="form.controlTitle" placeholder="自定义字段名称" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="是否必填" prop="isRequired" v-if="dynamicFormItems.includes('isRequired')"
                        :label-width="formLabelWidth">
            <el-switch v-model="form.isRequired"></el-switch>
          </el-form-item>

          <el-form-item label="pdf是否有下划线" prop="isUnderline" v-if="dynamicFormItems.includes('isUnderline')"
                        :label-width="formLabelWidth">
            <el-switch v-model="form.isUnderline"></el-switch>
          </el-form-item>
          <el-form-item label="是否可编辑" prop="isEdit" v-if="dynamicFormItems.includes('isEdit')"
                        :label-width="formLabelWidth">
            <el-switch v-model="form.isEdit"></el-switch>
          </el-form-item>
          <el-form-item label="默认展示长度" prop="showTextLength" v-if="dynamicFormItems.includes('showTextLength')"
                        :label-width="formLabelWidth">
            <el-input v-model="form.showTextLength" placeholder="默认展示长度" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="文本长度限制" prop="textLength" v-if="dynamicFormItems.includes('textLength')"
                        :label-width="formLabelWidth">
            <el-input v-model="form.textLength" placeholder="文本长度限制" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="日期格式" v-if="dynamicFormItems.includes('dateFormat')" :label-width="formLabelWidth">
            <el-radio-group v-model="form.dateFormat">
              <el-radio label="date">年月日</el-radio>
              <el-radio label="yearMonth">年月</el-radio>
              <el-radio label="year">年</el-radio>
              <el-radio label="datetime">年月日时分秒</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="展示形式" v-if="dynamicFormItems.includes('dateShowFormat')"
                        :label-width="formLabelWidth">
            <el-radio-group v-model="form.dateShowFormat">
              <el-radio label="cn">yyyy年MM月dd日 HH时mm分ss秒</el-radio>
              <el-radio label="standard">yyyy-MM-dd HH:mm:ss</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否自动生成" prop="isAutoData" :label-width="formLabelWidth">
            <el-switch v-model="form.isAutoData" @change="handleIsAutoDataChange"></el-switch>
          </el-form-item>
          <el-form-item label="数据来源" style="" prop="dataSource" v-if="form.isAutoData"
                        :label-width="formLabelWidth">
            <el-select v-model="form.dataSource" @change="handleDataSourceChange" placeholder="数据来源">
              <el-option label="手动填充" value="handFill"></el-option>
              <el-option label="系统中选择字段填充" value="systemTableFill"></el-option>
              <el-option label="API" value="apiFill"></el-option>
              <el-option label="填表日期" value="systemTimeFill"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="自动生成规则" prop="dataSourceRule" v-if="form.dataSource" :label-width="formLabelWidth">
            <el-input type="textarea" :readonly="form.dataSource === 'apiFill'" rows="8"
                      v-model="form.dataSourceRule"></el-input>
          </el-form-item>
          <div style="position: relative" v-if="form.dataSource">
            <button type="button" class="el-button el-button--text">
              <span class="systemTableFillClass" @click="systemTableFillAction"
                    v-if="form.dataSource==='systemTableFill'"> 插入系统字段 </span>
              <span class="apiFillClass" @click="apiFillAction('dataSource')"
                    v-if="form.dataSource==='apiFill'"> 配置API </span>
            </button>
          </div>

          <el-form-item label="枚举值来源" prop="enumDataSource" v-if="dynamicFormItems.includes('enumDataSource')"
                        :label-width="formLabelWidth">
            <el-select v-model="form.enumDataSource" @change="handleEnumDataSourceChange" placeholder="枚举值来源">
              <el-option label="手动填充" value="handFillEnum"></el-option>
              <el-option label="API" value="apiFillEnum"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自动生成规则" prop="enumDataSourceRule" v-if="form.enumDataSource"
                        :label-width="formLabelWidth">
            <el-input type="textarea" :readonly="form.enumDataSource === 'apiFillEnum'" rows="8"
                      v-model="form.enumDataSourceRule"></el-input>
          </el-form-item>
          <div style="position: relative" v-if="form.enumDataSource">
            <button type="button" class="el-button el-button--text">
              <span class="apiFillClass" @click="apiFillAction('enumDataSource')"
                    v-if="form.enumDataSource==='apiFillEnum'"> 配置API </span>
            </button>
          </div>
        </el-form>

      </template>
    </PlutoDialog>


    <PlutoDialog
      :visible.sync="ruleApiDialogVisible"
      :config="dialogApiConfigRule"
      @confirm="handleConfirmApiRuleAction"
    >
      <!-- 配置API对话框 -->
      <template v-slot:content>
        <el-form label-position="right" label-width="80px" :model="generateRuleForm">
          <el-form-item label="请求方式" :label-width="formLabelWidth">
            <el-select v-model="generateRuleForm.apiMethod" placeholder="请求方式">
              <el-option label="GET" value="GET"></el-option>
              <el-option label="POST" value="POST"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请求URL" :label-width="formLabelWidth">
            <el-input v-model="generateRuleForm.apiUrl"></el-input>
          </el-form-item>
          <el-form-item label="请求header" :label-width="formLabelWidth">
            <PlutoCodeEditor
              height="100px"
              ref="codeEditorHeader"
              v-model="generateRuleForm.apiHeader"
              placeholder="// 在这里编写API处理逻辑"
            />
            <!--          v-if="form.dataSource==='apiFill'" -->
          </el-form-item>
          <el-form-item label="POST请求参数" v-if="generateRuleForm.apiMethod=='POST'" :label-width="formLabelWidth">
            <PlutoCodeEditor
              height="110px"
              ref="codeEditorRequest"
              v-model="generateRuleForm.apiRequest"
              placeholder="// 在这里编写API处理逻辑"
            />
          </el-form-item>
          <el-form-item label="响应Response" :label-width="formLabelWidth">
            <PlutoCodeEditor
              ref="codeEditorResponse"
              height="220px"
              v-model="generateRuleForm.apiResponse"
              :first-line="firstLine"
              :last-line="lastLine"
              placeholder="// 在这里编写API处理逻辑"
              @change="handleCodeChange"
              @copy="handleCodeCopy"
            />
          </el-form-item>
        </el-form>
      </template>
    </PlutoDialog>


    <PlutoDialog
      :visible.sync="ruleSystemDialogVisible"
      :config="dialogSystemConfigRule"
      @confirm="handleConfirmSystemRuleAction"
    >
      <!-- 配置API对话框 -->
      <template v-slot:content>
        <PlutoTablePrint
          ref="refPlutoTable"
          title="系统字段"
          :columns="systemTable.columns"
          :table-data="systemTable.tableData"
          :total="systemTable.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @filter="handleFilter"
          :show-selection="true"
          :show-actions="false"
          :show-pagination="true"
          :page-sizes="[5, 10, 20, 50]"
          :default-page-size="5"
          :show-index="true"
        >

          <!--          @selection-change="handleSelectionChange"-->
          <!--          @print="handlePrint"-->
          <!--         -->
          <!--          @current-change="handleCurrentChange"-->
          <!--          @cancel="handleCancel"-->
          <!-- 自定义状态列 -->
          <!--          <template v-slot:status="scope">-->
          <!--            <el-tag :type="scope.row.status === '在职' ? 'success' : 'info'">-->
          <!--              {{ scope.row.status }}-->
          <!--            </el-tag>-->
          <!--          </template>-->

          <!-- 自定义操作列 -->
          <!--          <template v-slot:action="scope">-->
          <!--            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>-->
          <!--            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>-->
          <!--          </template>-->
        </PlutoTablePrint>


      </template>
    </PlutoDialog>

  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue';
import PlutoCodeEditor from '@/components/PlutoCodeEditor/PlutoCodeEditor.vue'
import PlutoDialog from "@/components/PlutoDialog/PlutoDialog.vue";
import PlutoTablePrint from "@/components/PlutoTablePrint/PlutoTablePrint.vue";

import * as api from './api'

export default {
  name: 'DOC_TEMPLATE_CONFIG',
  components: {
    PlutoTablePrint,
    PlutoDialog,
    Editor,
    PlutoCodeEditor
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogConfig: {
        title: '表单配置',
        width: '40%',
        contentHeight: 520,
      },
      form: {
        controlType: "1",
        controlKey: '',
        controlTitle: '',
        isUnderline: false,
        isEdit: false,
        textLength: '',
        isRequired: false,
        showTextLength: '',
        dateFormat: 'day',
        dateShowFormat: 'format_1',
        isAutoData: '',
        dataSource: '',
        dataSourceRule: '',
        enumDataSourceRule: '',
        enumDataSource: ''
      },
      ruleApiDialogVisible: false,
      ruleApiDialogType: 'dataSource',
      ruleSystemDialogVisible: false,
      firstLine: 'function filter(res) {',
      lastLine: '}',
      dialogApiConfigRule: {
        title: 'API规则编辑',
        width: '50%',
        contentHeight: 600
      },
      dialogSystemConfigRule: {
        title: '系统字段规则编辑',
        width: '50%',
        contentHeight: 550
      },

      generateRuleForm: {
        apiUrl: '',
        apiMethod: 'GET',
        apiHeader: '',
        apiRequest: '',
        apiResponse: ''
      },


      contentHtml: '',
      loading: false,
      dialogLoading: false,
      isUnderlineHasControlType: [1],
      formLabelWidth: '120px',
      templateInfo: {
        // documentDetails: [
        //   {
        //     formTemplateConfigMap: {},
        //     formTemplate: '',
        //     docTemplate: ''
        //   }
        // ],
        formTemplateConfigMap: {},
        formTemplate: '',
        docTemplate: '',
        templateCode: 'A058LASPB'
      },
      formTemplateConfigMapTemp: {},
      systemTable: {
        columns: [
          {prop: 'tableName', label: '表名'},
          {prop: 'tableComment', label: '表键值', width: '120'},
          {prop: 'fieldName', label: '字段键值'},
          {prop: 'fieldComment', label: '字段备注'}
        ],
        tableData: [],
        total: 0,
        filterParams: {
          pageNum: 1,
          pageSize: 5,
          search: ''
        },
      },


      rules: {
        controlType: [
          {required: true, message: '请选择控件类型', trigger: 'change'}
        ],
        controlKey: [
          {required: true, message: '请输入自定义key', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
                return;
              }

              // 必须以英文字母开头
              if (!/^[a-zA-Z]/.test(value)) {
                callback(new Error('必须以英文字母开头'));
                return;
              }

              // 只能包含字母、数字和下划线
              if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(value)) {
                callback(new Error('只能包含字母、数字和下划线，不能有特殊字符'));
                return;
              }

              callback();
            },
            trigger: 'blur'
          }
        ],
        controlTitle: [
          {required: true, message: '请输入自定义字段名称', trigger: 'blur'}
        ],
        showTextLength: [
          {
            required: false, // 改为非必填，通过动态验证控制
            validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入数字'));
                return;
              }

              // 只有当控件类型为输入框且值存在时才验证
              if (this.form.controlType === "1" && (value || value === 0)) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= 0) {
                  callback(new Error('数字必须大于0'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        textLength: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入数字'));
                return;
              }
              if (this.form.controlType === "1" && (value || value === 0)) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= 0) {
                  callback(new Error('数字必须大于0'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        isAutoData: [
          {
            required: false, // 改为非必填，通过动态验证控制
            validator: (rule, value, callback) => {
              if (value === true) {
                // 如果 isAutoData 为 true，则检查 generateRule 和 dataSource
                if (!this.form.dataSourceRule) {
                  callback(new Error('当启用自动填充时，生成规则为必填'));
                } else if (!this.form.dataSource) {
                  callback(new Error('当启用自动填充时，数据源为必填'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        dataSourceRule: [
          {
            required: false, // 改为非必填，通过动态验证控制
            validator: (rule, value, callback) => {
              console.log(value)
              if (this.form.isAutoData === true && !value) {
                callback(new Error('生成规则为必填'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        dataSource: [
          {
            required: false, // 改为非必填，通过动态验证控制
            validator: (rule, value, callback) => {
              if (this.form.isAutoData === true && !value) {
                callback(new Error('数据源为必填'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        enumDataSource: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (this.form.controlType === "3" && this.form.enumDataSource && !value) {
                callback(new Error('枚举值来源为必填'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        enumDataSourceRule: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (this.form.controlType === "3" && this.form.enumDataSource && !value) {
                callback(new Error('枚举值生成规则为必填'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      editorConfig: {
        height: 800,
        language: 'zh_CN',
        menubar: false,
        plugins: [
          'advlist autolink lists link image charmap print preview',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount',
          'contextmenu'
        ],
        toolbar: [
          // 'undo redo | cut copy paste pastetext | selectall | codesample  | searchreplace visualblocks fullscreen  print',
          'bold italic underline strikethrough subscript superscript | forecolor backcolor | code preview | removeformat fontselect fontsizeselect formatselect',
          'alignleft aligncenter alignright alignjustify | outdent indent | bullist numlist | checklist',
          'customFields table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol'
        ],

        // 关键配置：启用表格调整大小并保留样式
        table_resize: true,
        object_resizing: true,
        table_appearance_options: true,
        table_grid: true,
        // 关键配置：保留表格样式和属性
        table_style_by_css: false, // 不使用CSS样式，使用HTML属性
        table_use_colgroups: false,

        // 关键配置：允许所有表格属性
        valid_elements: '*[*]',

        extended_valid_elements: 'span[class|data-*|style|contenteditable|readonly|disabled],table[width|height|border|cellspacing|cellpadding|style|class|align],td[width|height|style|class|colspan|rowspan|align|valign],th[width|height|style|class|colspan|rowspan|align|valign],tr[style|class|align|valign]',
        verify_html: false,
        cleanup: false,
        trim_span_elements: false,

        // 允许自定义属性和元素
        valid_children: '+body[span],+span[span]',
        custom_elements: '~span',

        // 允许所有数据属性
        allow_script_urls: true,
        allow_unsafe_link_target: true,
        // 修正字体配置
        font_formats:
          '微软雅黑=Microsoft YaHei, sans-serif;' +
          '黑体=SimHei, sans-serif;' +
          '楷体=KaiTi, serif;' +
          '宋体=SimSun, serif;' +
          '仿宋=FangSong, serif;' +
          'Arial=Arial, sans-serif;' +
          'Times New Roman=Times New Roman, serif',
        fontsize_formats: '8px 10px 12px 14px 16px 18px 24px 36px 48px',

        // 修正 content_style
        content_style: `
        /* 设置编辑器主体字体   padding: 40px !important; */
          body.mce-content-body {
            width: 595px !important;
            min-height: 842px !important;
            margin: 20px auto !important;
            font-family: 'Microsoft YaHei', 'SimSun', sans-serif !important;
            background-color: white !important;
            box-sizing: border-box !important;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
            border-radius: 2px;
            position: relative;
          }
        /* 编辑器内表格样式 - 确保可见 width: 100% !important;  */
            table {
              border-collapse: collapse !important;
              border: 1px solid #000000 !important;
            }
            td, th {
              border: 1px solid #000000 !important;
              padding: 8px !important;
              min-width: 50px; /* 确保单元格有最小宽度 */
            }
          /* 设置整个编辑区域的背景色（A4纸以外的区域） */
          body {
            background-color: #e8f4fd !important; /* A4纸以外的区域用浅蓝色 */
          }
              /* 自定义字段样式 */
              .edit-able {
                outline: none !important;
                box-shadow: none !important;
                display: inline-block;
                width: 24px;
                height: 24px;
                padding: 0;
                background-repeat: no-repeat;
                background-size: 20px;
                background-position: center;
                background-image: url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/edit_gear.640efb88.svg");
                cursor: pointer;
                border-radius: 3px;
               }
              .edit-able.configured {
                cursor: pointer;
                background-image: url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/edit_gear.640efb88.svg");
               }
               .input-control{
                  outline: none !important;
                  cursor: pointer;
                  box-shadow: none !important;
                  border-bottom: 1px solid #000000;
                  display: inline-block;
                  padding: 0;
                }
              .day-control{
                outline: none !important;
                box-shadow: none !important;
                padding: 5px 12px;
                background-position: center;
                background-size: 25px;
                background-repeat: no-repeat;
                cursor: pointer;
                }
               .signal-select-control{
                  outline: none !important;
                  box-shadow: none !important;
                  border-bottom: 1px solid;
                  cursor: pointer;
                  &::before {
                    color: #ccc;
                    content: '请选择';
                  }

                  &::after {
                    padding: 0;
                    color: #ccc;
                    content: '▽';
                    vertical-align: baseline;
                    text-transform: none;
                    font-weight: 400;
                    font-style: normal;
                    font-variant: normal;
                    font-family: element-icons !important;
                    line-height: 1;
                    -webkit-font-smoothing: antialiased;
                    -moz-osx-font-smoothing: grayscale;
                  }
            }

        `,

        contextmenu: "link | mycustomitem",

        setup: (editor) => {
          // 添加自定义字段菜单项
          editor.ui.registry.addMenuItem('mycustomitem', {
            text: '插入自定义字段',
            icon: 'link',
            onAction: () => {
              const fieldId = 'field_' + Date.now();
              const contentToInsert = `
             <span contenteditable="false" style="outline:none; cursor: pointer;" class="control-parent-span">
               <span class="edit-able configured" contenteditable="false" data-control-key="" data-custominsert="" data-field-id="${fieldId}"></span>
             </span>`;
              // 使用 insertHTML 方法替代 insertContent
              // editor.insertContent(contentToInsert);
              editor.selection.setContent(contentToInsert, {format: 'html'});
            }
          });

          // 点击字段时打开弹窗
          editor.on('click', (e) => {
            const target = e.target;
            if (target.classList && target.classList.contains('edit-able')) {
              this.handleFormDetailAction(target);
            }
          });

          // 关键：监听表格变化，确保宽度被保留
          editor.on('ObjectResized', function (e) {
            if (e.target.nodeName === 'TABLE' || e.target.nodeName === 'TD' || e.target.nodeName === 'TH') {
              const element = e.target;
              // 确保宽度属性被设置
              if (e.width) {
                element.setAttribute('width', e.width + 'px');
              }
              if (e.height) {
                element.setAttribute('height', e.height + 'px');
              }
            }
          });


        },

        branding: false,
        elementpath: false,
        statusbar: true,
        resize: true,
        paste_data_images: true,
        images_upload_url: '/api/upload',
        automatic_uploads: true,
        // 关键：允许所有样式
        valid_styles: {
          '*': 'width,height,min-width,min-height,max-width,max-height,' +
            'border,border-top,border-right,border-bottom,border-left,border-width,border-style,border-color,' +
            'padding,padding-top,padding-right,padding-bottom,padding-left,' +
            'margin,margin-top,margin-right,margin-bottom,margin-left,' +
            'font-family,font-size,font-weight,font-style,font-variant,text-decoration,text-align,text-transform,line-height,letter-spacing,' +
            'color,background-color,background-image,background-repeat,background-size,background-position,background-attachment,' +
            'display,visibility,opacity,position,top,right,bottom,left,z-index,' +
            'float,clear,overflow,overflow-x,overflow-y,' +
            'box-sizing,box-shadow,text-shadow,' +
            'cursor,user-select,pointer-events,' +
            'border-collapse,border-spacing,table-layout,' +
            'vertical-align,white-space,word-wrap,word-break,' +
            'outline,outline-width,outline-style,outline-color,' +
            'list-style,list-style-type,list-style-position,list-style-image,' +
            'transform,transition,animation'
        },
        // 保护特定的类和属性
        // protect: [
        //   /class=".*?(insert-elem|input-control|day-control|signal-select-control|edit-able).*?"/g,
        //   /data-control-key=".*?"/g,
        //   /data-control-type=".*?"/g,
        //   /contenteditable="false"/g,
        //   /readonly="true"/g,
        //   /disabled="true"/g
        // ],
      }
    };
  },
  computed: {
    // 根据控件类型动态显示表单项
    dynamicFormItems() {
      if (this.form.controlType === "1") {
        // 输入框类型显示的项
        return ['controlKey', 'controlTitle', 'isRequired', 'isUnderline', 'isEdit', 'showTextLength', 'textLength'];
      } else if (this.form.controlType === "2") {
        // 日期时间类型显示的项
        return ['controlKey', 'controlTitle', 'isRequired', 'isUnderline', 'isEdit', 'dateFormat', 'dateShowFormat'];
      } else if (this.form.controlType === "3") {
        // 下拉框类型显示的项
        return ['controlKey', 'controlTitle', 'isRequired', 'isUnderline', 'isEdit', 'enumDataSource'];
      }
      return [];
    }
  },
  methods: {


    resetGenerateRuleAction() {
      this.generateRuleForm = {
        apiUrl: '',
        apiMethod: 'GET',
        apiHeader: '',
        apiRequest: '',
        apiResponse: ''
      }
    },
    apiFillAction(param) {
      this.ruleApiDialogType = param
      console.log('当前API框是:', param)
      if (this.ruleApiDialogType === "dataSource") {
        if (this.form.dataSourceRule) {
          this.generateRuleForm = JSON.parse(this.form.dataSourceRule);
        }
      }
      if (this.ruleApiDialogType === "enumDataSource") {
        if (this.form.enumDataSourceRule) {
          this.generateRuleForm = JSON.parse(this.form.enumDataSourceRule);
        }
      }
      this.ruleApiDialogVisible = true;
    },

    handleConfirmApiRuleAction() {
      console.log('当前API框是:', this.ruleApiDialogType)
      if (this.ruleApiDialogType === "dataSource") {
        this.form.dataSourceRule = JSON.stringify(this.generateRuleForm, null, 2)
        console.log('保存的代码:', this.form.dataSourceRule)
      }
      if (this.ruleApiDialogType === "enumDataSource") {
        this.form.enumDataSourceRule = JSON.stringify(this.generateRuleForm, null, 2)
        console.log('保存的代码:', this.form.enumDataSourceRule)
      }
      console.log('22222222:', this.form.enumDataSourceRule)

      this.ruleApiDialogVisible = false
      // this.resetGenerateRuleAction()
      // this.$message.success('代码保存成功');
    },
    systemTableFillAction() {
      this.ruleSystemDialogVisible = true;
    },
    handleConfirmSystemRuleAction() {
      // 通过ref获取表格组件实例，然后调用getSelectedData方法获取选中的数据
      if (this.$refs.refPlutoTable) {
        const selectedData = this.$refs.refPlutoTable.getSelectedData();
        // 保留 ${} 格式的字符串
        this.form.dataSourceRule = selectedData.map(field =>
          `\${${field.tableName}.${field.fieldName}}`
        ).join(",");

        console.log('选中的系统字段数据:', this.form.dataSourceRule);
        // 这里可以处理选中的数据，比如赋值给表单等
        // 然后关闭对话框
        this.ruleSystemDialogVisible = false;
      } else {
        this.$message.warning('没有选中数据');
      }
    },
    handleDataSourceChange() {
      console.log('数据源变更:', this.form.dataSource)
      this.form.dataSourceRule = '';
      this.resetGenerateRuleAction()
    },
    handleEnumDataSourceChange() {
      this.form.enumDataSourceRule = '';
      this.resetGenerateRuleAction()
    },
    handleIsAutoDataChange() {
      if (!this.form.isAutoData) {
        this.form.dataSource = '';
        this.form.dataSourceRule = '';
      }
    },
    // 处理控件类型变更
    handleControlTypeChange(value) {
      console.log('控件类型变更:', value);
      // 重置表单，保留控件类型
      const controlType = value; // 使用传入的新值
      this.resetFormAction();
      this.form.controlType = controlType;

      // 根据控件类型设置默认值
      if (value === "1") {
        // 输入框默认值
        this.form.isUnderline = false;
        this.form.isEdit = false;
        this.form.showTextLength = '';
        this.form.textLength = '';
      } else if (value === "2") {
        // 日期时间默认值
        this.form.dateFormat = 'day';
        this.form.dateShowFormat = 'format_1';
        // 日期类型不需要这些字段，可以清空
        this.form.isUnderline = false;
        this.form.isEdit = false;
        this.form.showTextLength = '';
        this.form.textLength = '';
      }
    },

    resetFormAction() {
      this.form = {
        controlType: this.form.controlType,
        controlKey: '',
        controlTitle: '',
        isUnderline: false,
        isEdit: false,
        textLength: '',
        isRequired: false,
        showTextLength: '',
        dateFormat: 'day',
        dateShowFormat: 'format_1',
        isAutoData: false,
        dataSource: '',
        dataSourceRule: '',
        enumDataSourceRule: '',
        enumDataSource: ''
      }
    },
    // 处理字段点击事件
    handleFormDetailAction(fieldElement) {
      const fieldType = fieldElement.getAttribute('data-control-key');
      this.currentField = fieldElement;
      if (fieldType) {
        // 确保 controlType 是字符串类型
        this.form = {...this.templateInfo.formTemplateConfigMap[fieldType]};
        console.log('当前字段:', this.templateInfo)
        if (this.form.dataSourceRule && this.form.dataSource === 'apiFill') {
          this.generateRuleForm = JSON.parse(this.form.dataSourceRule);
        }
        this.pageTableAndColumList();
      } else {
        this.resetFormAction()
      }
      this.dialogFormVisible = true;
      console.log('点击了字段:', fieldType, fieldElement);
    },

    handleConfirmConfigAction() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 获取编辑器实例
          const editor = tinymce.get(0) || tinymce.activeEditor;
          if (editor) {
            const formData = {...this.form}; // 保存表单数据副本
            // 在异步操作前保存当前字段的引用
            const currentField = this.currentField;
            const existingElements = editor.getBody().querySelectorAll(`span.edit-able.configured[data-control-type="${formData.controlType}"][data-control-key="${formData.controlKey}"]`);
            let duplicateExists = false;
            existingElements.forEach(element => {
              // 排除当前正在编辑的元素
              if (element !== this.currentField) {
                duplicateExists = true;
              }
            });
            if (duplicateExists) {
              this.$message.error(`控件键名 "${this.form.controlKey}" 已存在，请使用其他键名`);
              return false;
            }

            this.dialogLoading = true;

            // 模拟异步操作
            if (currentField) {
              // 更新当前字段的属性
              currentField.setAttribute('data-control-key', formData.controlKey);
              currentField.setAttribute('data-control-type', formData.controlType);

              // 根据控件类型生成不同的样式和内容
              let style = '';
              if (formData.controlType === "1") {
                style = `min-width: ${parseInt(formData.showTextLength) * 12 || 10}px;`;

                const existingSpans = editor.getBody().querySelectorAll(`span.edit-able.configured[data-control-type="1"][data-control-key="${formData.controlKey}"]`);
                existingSpans.forEach(span => {
                  // 获取所有兄弟元素（排除自身）
                  const siblings = Array.from(span.parentNode.children).filter(child => child !== span);
                  // 删除所有兄弟元素
                  siblings.forEach(sibling => {
                    editor.dom.remove(sibling);
                  });
                });
                // 方法3: 如果要在前面插入并保留原字段，使用以下代码
                const newNode = editor.dom.create('span', {
                  'data-control-key': formData.controlKey,
                  'data-control-type': formData.controlType,
                  'class': 'insert-elem input-control',
                  'contenteditable': 'false',
                  'style': style
                }, "");
                currentField.parentNode.insertBefore(newNode, currentField);

              }

              if (formData.controlType === "2") {
                style = ``;
                if (formData.dateFormat === "day") {
                  style = `background-image:url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/date_icon.1cd1b844.svg");`;
                }
                if (formData.dateFormat === "month") {
                  style = `background-image:url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/date_icon.1cd1b844.svg");`;
                }
                if (formData.dateFormat === "year") {
                  style = `background-image:url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/date_icon.1cd1b844.svg");`;
                }
                if (formData.dateFormat === "datetime") {
                  style = `background-image:url("http://192.168.1.147:9152/sub-sys/template-doc/static-hash/img/datetime_icon.602406fa.svg");`;
                }


                const existingSpans = editor.getBody().querySelectorAll(`span.edit-able.configured[data-control-type="2"][data-control-key="${formData.controlKey}"]`);
                existingSpans.forEach(span => {
                  // 获取所有兄弟元素（排除自身）
                  const siblings = Array.from(span.parentNode.children).filter(child => child !== span);
                  // 删除所有兄弟元素
                  siblings.forEach(sibling => {
                    editor.dom.remove(sibling);
                  });
                });


                // 方法3: 如果要在前面插入并保留原字段，使用以下代码
                const newNode = editor.dom.create('span', {
                  'data-control-key': formData.controlKey,
                  'data-control-type': formData.controlType,
                  'contenteditable': 'false',
                  'class': 'day-control',
                  'style': style
                }, "");
                currentField.parentNode.insertBefore(newNode, currentField);

              }

              if (formData.controlType === "3") {
                style = ``;
                const existingSpans = editor.getBody().querySelectorAll(`span.edit-able.configured[data-control-type="3"][data-control-key="${formData.controlKey}"]`);
                existingSpans.forEach(span => {
                  // 获取所有兄弟元素（排除自身）
                  const siblings = Array.from(span.parentNode.children).filter(child => child !== span);
                  // 删除所有兄弟元素
                  siblings.forEach(sibling => {
                    editor.dom.remove(sibling);
                  });
                });
                const newNode = editor.dom.create('span', {
                  'data-control-key': formData.controlKey,
                  'data-control-type': formData.controlType,
                  'contenteditable': 'false',
                  'class': 'signal-select-control',
                  'style': style
                }, "");
                currentField.parentNode.insertBefore(newNode, currentField);
              }
            }
            // 更新表单配置
            this.formTemplateConfigMapTemp[formData.controlKey] = formData;
          }
          this.$message.success('保存成功');
          this.dialogFormVisible = false;
          this.dialogLoading = false;
          this.currentField = null;
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    addAction() {
      const editor = tinymce.get(0) || tinymce.activeEditor;
      if (editor) {
        // 获取完整的 HTML 内容（包括所有属性）
        const rawContent = editor.getContent({format: 'raw'});
        // 处理所有表格，确保有 border-collapse: collapse
        console.log('=== 编辑器中的表格 ===');
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = rawContent;
        const tables = tempDiv.querySelectorAll('table');

        tables.forEach((table, index) => {
          let currentStyle = table.getAttribute('style') || '';
          if (!currentStyle.includes('border-collapse')) {
            currentStyle += ' border-collapse: collapse;';
          }
          table.setAttribute('style', currentStyle.trim());
        });

        // 更新 this.content
        this.contentHtml = tempDiv.innerHTML;
      }

      // 保存 Thymeleaf 模板（用于渲染）
      this.templateInfo.templateName = "";
      this.templateInfo.docTemplate = this.convertWithDOMParser(this.contentHtml);
      this.templateInfo.formTemplate = this.contentHtml;
      console.log('contentHtml🎁🎁🎁🎁🎁：', this.contentHtml)
      console.log('docTemplate：🚗🚗🚗🚗🚗🚗', this.templateInfo.docTemplate)
      const parser = new DOMParser();
      const doc = parser.parseFromString(this.contentHtml, 'text/html');
      const controlKeys = doc.querySelectorAll('span.edit-able.configured[data-control-key]');
      const controlKeyValues = Array.from(controlKeys).map(span => span.getAttribute('data-control-key'));
      console.log('controlKeyValues', controlKeyValues)
      console.log('formTemplateConfigMapTemp', this.formTemplateConfigMapTemp)

      // 修正：直接使用 this.formTemplateConfigMapTemp，不要 JSON.stringify
      this.templateInfo.formTemplateConfigMap = Object.keys(this.formTemplateConfigMapTemp)
        .filter(key => controlKeyValues.includes(key))
        .reduce((result, key) => {
          result[key] = this.formTemplateConfigMapTemp[key];
          return result;
        }, {});
      console.log('过滤后的 formTemplateConfigMapTemp', this.templateInfo.formTemplateConfigMap);
      if (this.loading) {
        return;
      }
      this.loading = false;
      api.saveDcoTemplate(this.templateInfo).then(res => {
        if (200 === res.code) {
          this.loading = true
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    convertWithDOMParser(html) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');

      // 一步到位：找到所有需要处理的元素并转换
      const fieldsToProcess = doc.querySelectorAll('span.edit-able.configured[data-control-key]');

      fieldsToProcess.forEach(field => {
        const controlKey = field.getAttribute('data-control-key');
        const controlType = field.getAttribute('data-control-type');
        // 创建 thymeleaf 字段
        const thymeleafField = this.createThymeleafField(field, controlKey, controlType);
        field.outerHTML = thymeleafField;
      });

      // 删除其他没有 edit-able configured 但带有 data-control-key 的元素
      const fieldsToRemove = doc.querySelectorAll('span[data-control-key]:not(.edit-able.configured)');
      fieldsToRemove.forEach(field => field.remove());

      // 关键：保护所有表格和单元格的宽度属性
      this.protectAllWidths(doc);

      // 删除 </br> 标签
      return doc.body.innerHTML;
    },
    createThymeleafField(field, controlKey, controlType) {
      if (!controlKey) return '<span style="color: red;font-family:Microsoft YaHei,serif">[未配置字段]</span>';

      const clonedField = field.cloneNode(true);

      // 清理属性
      ['data-mce-style', 'data-custominsert', 'data-field-id'].forEach(attr => {
        clonedField.removeAttribute(attr);
      });
      // 移除不需要的样式（包括小手光标）
      ['cursor', 'background-image', 'padding', 'background-repeat', 'background-size', 'background-position'].forEach(styleProp => {
        clonedField.style.removeProperty(styleProp);
      });

      // 设置 thymeleaf 属性
      clonedField.setAttribute('th:text', `*{${controlKey}}`);

      // 设置下划线
      const config = this.formTemplateConfigMapTemp[controlKey];
      if (config?.isUnderline) {
        clonedField.style.borderBottom = '1px solid #000';
      }
      return clonedField.outerHTML;
    },

    // 新增：保护所有宽度属性
    protectAllWidths(doc) {
      // 保护表格宽度
      const tables = doc.querySelectorAll('table');
      tables.forEach(table => {
        // 如果表格有样式宽度但没有属性宽度，复制过去
        if (table.style.width && !table.getAttribute('width')) {
          table.setAttribute('width', table.style.width);
        }
        // 确保表格有基础属性
        if (!table.getAttribute('border')) table.setAttribute('border', '1');
        if (!table.getAttribute('cellspacing')) table.setAttribute('cellspacing', '0');
        if (!table.getAttribute('cellpadding')) table.setAttribute('cellpadding', '8');
      });

      // 保护单元格宽度
      const cells = doc.querySelectorAll('td, th');
      cells.forEach(cell => {
        if (cell.style.width && !cell.getAttribute('width')) {
          cell.setAttribute('width', cell.style.width);
        }
        if (cell.style.height && !cell.getAttribute('height')) {
          cell.setAttribute('height', cell.style.height);
        }
      });
    },

    pageTableAndColumList() {
      api.pageTableAndColumList(this.systemTable.filterParams).then(res => {
        if (200 === res.code) {
          this.loading = true;
          this.systemTable.tableData = res.data.list;
          this.systemTable.total = res.data.total;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    cancelAction() {
      this.$router.push('/process/doctemplate'); // 替换为您想返回的具体路径
    },

    // 分页大小变化
    handleSizeChange(pageSize) {
      this.systemTable.filterParams.pageSize = pageSize;
      this.systemTable.filterParams.pageNum = 1;
      this.pageTableAndColumList();
    },
    // 当前页变化
    handleCurrentChange(pageNum) {
      this.systemTable.filterParams.pageNum = pageNum;
      this.pageTableAndColumList();
    },

    // 筛选处理
    handleFilter(filterText) {
      this.systemTable.filterParams.search = filterText;
      this.systemTable.filterParams.pageNum = 1;
      this.pageTableAndColumList();
    },


    // 处理代码变化
    handleCodeChange(fullCode) {
      console.log('代码发生变化:', fullCode);
    },

    // 处理代码复制
    handleCodeCopy(fullCode) {
      this.$message.success('代码已复制到剪贴板');
    },

    templateDetailAction() {
      this.templateInfo.templateCode = this.$route.query.templateCode;
      api.getTemplateData(this.templateInfo.templateCode).then(res => {
        if (200 === res.code) {
          this.loading = true;
          this.templateInfo.formTemplate = res.data.formTemplate;
          this.templateInfo.formTemplateConfigMap = res.data.formTemplateConfigMap;
          this.contentHtml = res.data.formTemplate;
          console.log('接口返回的HTML😍😍😍😍😍😍:', res.data.formTemplate);
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
  },
  mounted() {
    this.templateDetailAction();
  }
};
</script>

<style lang="scss" scoped>




::v-deep .mce-content-body {
  font-family: 'MicrosoftYaHei', 'SimSun', sans-serif !important;
}


/* 富文本编辑器容器 - A4纸以外的区域背景色 */
::v-deep .tox-tinymce {
  background-color: #e8f4fd !important; /* 浅蓝色背景 */
  padding: 0 !important;
}

/* 编辑区域iframe */
::v-deep .tox-edit-area__iframe {
  background-color: #e8f4fd !important; /* 浅蓝色背景 */
}

/* 编辑区域 */
::v-deep .tox-edit-area {
  background-color: #e8f4fd !important; /* 浅蓝色背景 */
}


.apiFillClass {
  position: absolute;
  left: 56px;
  top: -145px;
}

.systemTableFillClass {
  position: absolute;
  left: 23px;
  top: -145px;
}

.fixed-header {
  text-align: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: white;
  padding: 10px 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.content-wrapper {
  //margin-top: 60px; /* 根据按钮行高度调整 */
  //height: calc(100vh - 60px); /* 全屏高度减去按钮行高度 */
}
</style>
